//
//  NSObject+hook.m
//  yuanjiang
//
//  Created by YuanJiang on 2019/9/19.
//  Copyright © 2019 llbt. All rights reserved.
//

#import "NSObject+hook.h"
#import <objc/runtime.h>

/**
 setValueForkey  和  setObjectForkey区别
 
 */


const char *kPropertyListKey = "kPropertyListKey";

@implementation NSObject (hook)

+ (instancetype)modelWithDictionary:(NSDictionary *)dictionary
{
    id objc = [[self alloc] init];
    NSArray *arr = [self yj_PropertyList];
    
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([arr containsObject:key]) {
//            [objc setObject:obj forKey:key];
            [objc setValue:obj forKey:key];
        }
    }];
    
    return objc;
}

- (NSArray *)yj_PropertyList
{
    NSArray *ptyList = objc_getAssociatedObject(self, kPropertyListKey);
    if (ptyList) {
        return ptyList;
    }
    
    unsigned int outCount = 0;
    objc_property_t *propertyList = class_copyPropertyList([self class], &outCount);
    NSMutableArray *mtArray = [NSMutableArray array];
    for (unsigned int i=0; i<outCount; i++) {
        objc_property_t property = propertyList[i];
       const char *propertyName_C = property_getName(property);
       //将c字符串转换为oc字符串
        NSString *ocStr = [NSString stringWithCString:propertyName_C encoding:NSUTF8StringEncoding];
        [mtArray addObject:ocStr];
    }
    //设置关联对象
    objc_setAssociatedObject(self, kPropertyListKey, mtArray.copy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    free(propertyList);
    return mtArray.copy;
}

@end
